<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <title>K8s Web Terminal</title>
    <style>
        body { font-family: sans-serif; padding: 20px; }
        select, input, button { margin: 8px 0; padding: 6px; }
        .terminal-container { height: 300px; width: 100%; }
    </style>
    <link rel="stylesheet" href="./css/xterm.css">
    <script src="./js/xterm.min.js"></script>
</head>
<body>
<h2>Kubernetes Web Terminal</h2>

<label>Namespace:</label>
<input type="text" id="namespace" value="default" />
<button onclick="loadPods()">加载 Pods</button>

<br>

<label>Pod:</label>
<select id="pod" onchange="updateContainers()"></select>

<br>

<label>Container:</label>
<select id="container"></select>

<br>

<button onclick="connectTerminal()">连接终端</button>

<h3>终端输出</h3>
<div id="terminal" class="terminal-container"></div>

<script>
    let podMap = {};

    function loadPods() {
      const ns = document.getElementById("namespace").value;
      fetch(`/api/pods?namespace=${ns}`)
        .then(res => res.json())
        .then(data => {
          podMap = {};
          const podSelect = document.getElementById("pod");
          podSelect.innerHTML = "";
          data.forEach(item => {
            podMap[item.podName] = item.containers;
            const opt = document.createElement("option");
            opt.value = item.podName;
            opt.text = item.podName;
            podSelect.appendChild(opt);
          });
          updateContainers();
        });
    }

    function updateContainers() {
      const pod = document.getElementById("pod").value;
      const containerSelect = document.getElementById("container");
      containerSelect.innerHTML = "";
      (podMap[pod] || []).forEach(name => {
        const opt = document.createElement("option");
        opt.value = name;
        opt.text = name;
        containerSelect.appendChild(opt);
      });
    }

    function connectTerminal() {
      const ns = document.getElementById("namespace").value;
      const pod = document.getElementById("pod").value;
      const container = document.getElementById("container").value;

      const params = new URLSearchParams({ namespace: ns, pod, container });

      fetch("/api/terminal/authorize", {
        method: "POST",
        headers: { "Content-Type": "application/x-www-form-urlencoded" },
        body: params
      })
        .then(res => res.json())
        .then(data => {
          const uid = data.uid;
          const ws = new WebSocket(`ws://${location.host}/ws/terminal?uid=${uid}`);

          const termContainer = document.getElementById("terminal");
          const terminal = new Terminal({
            cols: 80,
            rows: 24,
            cursorBlink: true,
            fontFamily: 'monospace'
          });

          terminal.open(termContainer);
          terminal.write("正在连接...\n");

          ws.onopen = () => {
            terminal.write("[连接成功]\n");
            // 监听键盘输入：
            document.onkeydown = e => {
              if (ws.readyState === WebSocket.OPEN) {
                const char = e.key;
                if (char.length === 1 || char === "Enter") {
                  ws.send(char === "Enter" ? "\n" : char);
                }
              }
            };
          };

          ws.onmessage = e => {
            terminal.write(e.data);
          };

          ws.onclose = () => {
            terminal.write("\n[连接关闭]");
          };
        });
    }
</script>
</body>
</html>
